<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml" lang="">
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" method="POST" action="">
            <div class="layui-form-item">

                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input id="username" type="text" name="username" placeholder="请输入用户名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-inline">
                        <input id="name" type="text" name="name" placeholder="请输入姓名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-md " lay-submit lay-filter="user-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="user-table" lay-filter="user-table"></table>
    </div>
</div>

<script type="text/html" id="user-toolbar">
    <button class="layui-btn  layui-btn-sm" lay-event="add" sa:hasPermission="user_add">
        <i class="layui-icon layui-icon-add-1"></i>
        新增
    </button>
    <button id="uploadExcel" class="layui-btn   layui-btn-sm" sa:hasPermission="user_import">
        <i class="layui-icon layui-icon-table"></i>
        导入
    </button>
    <a th:href="@{/pear/user.xlsx}" download="user.xlsx" id="downloadExcel"
       class="layui-btn  layui-btn-sm">
        <i class="layui-icon layui-icon-table"></i>
        下载模版
    </a>
</script>

<script type="text/html" id="user-bar">
    <button class="layui-btn  layui-btn-sm" sa:hasPermission="user_update" lay-event="edit"><i
            class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-warming layui-btn-sm" sa:hasPermission="user_reset_pwd" lay-event="resetPwd"><i
            class="layui-icon layui-icon-set"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" sa:hasPermission="user_delete" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i>
    </button>
    <button class="layui-btn layui-bg-blue layui-btn-sm" sa:hasPermission="fp_role" lay-event="role"><i
            class="layui-icon layui-icon-slider"></i>
    </button>
</script>

<script type="text/html" id="user-enable">
    <input type="checkbox" name="status" value="{{d.userId}}" lay-skin="switch" lay-text="启用|禁用"
           sa:hasPermission="user_enable"
           lay-filter="user-enable" {{ d.status== 0 ? 'checked' : '' }} />
</script>

<script type="text/html" id="user-sex">
    {{#if (d.sex == 1) { }}
    <span>男</span>
    {{# }else if(d.sex == 2){ }}
    <span>女</span>
    {{# } }}
</script>
<script type="text/html" id="user-createTime">
    {{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}
</script>

<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/layui/layarea.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['table', 'form', 'jquery', 'upload'], function () {
        let baseURL = /*[[@{/}]]*/ '';
        let table = layui.table;
        let form = layui.form;
        let $ = layui.jquery;
        let upload = layui.upload;
        let cols = [
            [{checkbox: true},
                {title: '姓名', field: 'name', align: 'left'},
                {title: '用户名', field: 'username', align: 'left'},
                {title: '性别', field: 'sex', align: 'left', templet: '#user-sex', sort: true},
                {title: '年龄', field: 'age', align: 'left'},
                {
                    title: '电话', field: 'phone', align: 'left', templet: function (e) {
                        return e.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
                    }
                },
                {title: '邮箱', field: 'email', align: 'left'},
                {
                    title: '部门',
                    field: 'departmentList',
                    align: 'left',
                    templet: function (d) {
                        // 如果用户属于多个部门，将部门名称用逗号分隔显示
                        if (d.departmentList && d.departmentList.length > 0) {
                            return d.departmentList.map(dept => dept.departmentName).join(', ');
                        } else {
                            return '无部门';
                        }
                    }
                },
                {title: '地址', field: 'area', align: 'left'},
                {
                    title: '头像', field: 'avatar', align: 'left', templet: function (d) {
                        return "<img style='width:50px;height:50px;' src='" + baseURL + d.avatar + "'/>"
                    }
                },
                {title: '启用', field: 'status', align: 'left', templet: '#user-enable'},
                {title: '注册时间', field: 'createTime', align: 'left', templet: '#user-createTime'},
                {title: '操作', toolbar: '#user-bar', align: 'center', width: 240}
            ]
        ]
        $.ajax({
            url: baseURL + 'department/session/getDepartmentId', // 后端接口地址
            type: 'get',
            contentType: 'application/json',
            success: function (response) {
                table.render({
                    elem: '#user-table',
                    url: baseURL + 'user/list?departmentId=' + response.data,
                    request: {
                        pageName: 'pageNum',
                        limitName: 'pageSize'
                    },
                    type: 'get',
                    page: true,
                    curr: 1,
                    cols: cols,
                    skin: 'line',
                    toolbar: '#user-toolbar',
                    limits: [5, 10, 15, 20],
                    parseData: function (res) {// 对从后端获得的数据进行规范，最后返回四个键值对
                        return {
                            "code": res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": res.data.total,
                            "data": res.data.list, //解析数据列表
                        };
                    },
                    response: {
                        statusName: "code",
                        msgName: "msg",
                        statusCode: 1000,
                        dataName: "data"
                    },
                });

            }
        })
        table.on('tool(user-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj);
            } else if (obj.event === 'resetPwd') {
                window.resetPwd(obj);
            } else if (obj.event === 'role') {
                window.role(obj);
            }
        });

        table.on('toolbar(user-table)', function (obj) {
            if (obj.event === 'add') {
                window.add();
            }
        });

        form.on('submit(user-query)', function (data) {
            let username = data.field.username;
            let name = data.field.name;
            let role = data.field.role;
            table.reload('user-table', {
                page: {
                    curr: 1
                },
                where: {
                    username: username,
                    name: name,
                    role: role
                }
            })
            return false;
        });
        document.getElementById('resetBtn').addEventListener('click', function () {
            // 重新加载表格，不带任何过滤条件
            table.reload('user-table', {
                where: {}, // 清除过滤条件
                page: {curr: 1} // 重新从第一页开始
            });
        });
        form.on('switch(user-enable)', function (obj) {
            const userId = obj.value;
            $.ajax({
                url: baseURL + 'user/enable/' + userId,
                type: 'post'
            })
        });

        window.add = function () {

            layer.open({
                type: 2,
                title: '用户新增',
                shade: 0.1,
                area: ['700px', '750px'],
                content: 'user-add'
            });
        }
        let un;
        let roleList;
        let departmentRoleList;
        window.role = function (obj) {

            console.log(obj.data);
            window.userId = obj.data.userId
            $.ajax({
                url: baseURL + "user/getUserById/" + obj.data.userId,
                type: 'get',
                success: function (res) {
                    un = res.data.username
                }
            })
            $.ajax({
                url: baseURL + "user/getRoleByUserId?userId=" + obj.data.userId,
                type: 'get',
                success: function (res) {
                    roleList = res.data && res.data.length > 0
                        ? res.data.map(role => role.roleName).join(',')
                        : '无个人角色';
                }
            })
            $.ajax({
                url: baseURL + "user/getUserDepartmentRoles?userId=" + obj.data.userId,
                type: 'get',
                success: function (res) {

                    departmentRoleList = res.data && res.data.length > 0
                        ? res.data.join(',')
                        : '无部门角色';
                    $.ajax({
                        url: baseURL + 'department/getDepartmentIdsByUserId?userId=' + obj.data.userId, // 后端接口地址
                        type: 'GET',
                        dataType: 'json',
                        success: function (data) {
                            layer.open({
                                type: 2,
                                title: '角色分配',
                                shade: 0.1,
                                area: ['700px', '600px'],
                                content: 'user-role',
                                success: function (layero, index) {

                                    // 数据回显
                                    let body = layer.getChildFrame('body', index);
                                    let iframeWin = layero.find('iframe')[0].contentWindow;
                                    let select = body.find('#department');
                                    let department = data.data;
                                    // 清空下拉框并添加选项
                                    select.empty().append('<option value="">请选择部门</option>');
                                    $.each(department, function (index, dept) {
                                        select.append('<option value="' + dept.departmentId + '">' + dept.departmentName + '</option>');
                                    });
                                    iframeWin.layui.form.render('select');
                                    body.find('#current-username').val(un);
                                    body.find('#current-person-roles').val(roleList)
                                    body.find('#current-department-role').val(departmentRoleList)
                                }
                            });

                        },
                        error: function () {
                            layer.msg('加载部门信息失败', {icon: 2});
                        }
                    });
                }
            })

        }

        window.edit = function (obj) {
            console.log(obj.data);
            $.ajax({
                url: baseURL + 'user/getRoleIdsByUserId',
                type: 'get',
                data: {userId: obj.data.userId},
                success: function (data) {
                    window.valueList = data.data
                }
            })
            window.userId = obj.data.userId
            window.avatar = obj.data.avatar
            window.area = obj.data.area
            // 加载部门列表
            $.ajax({
                url: baseURL + "department/getDepartmentIdsByUserId?userId=" + obj.data.userId,
                type: 'get',
                success: function (res) {
                    window.departmentList = res.data.map(item => item.departmentId);
                    console.log(window.departmentList)
                }
            })
            // 打开编辑模态框
            layer.open({
                type: 2,
                title: '用户修改',
                shade: 0.1,
                shadeClose: true,
                area: ['900px', '680px'],
                content: 'user-edit', // 子页面的 URL
                success: function (layero, index) {
                    // 数据回显
                    let body = layer.getChildFrame('body', index);
                    let iframeWin = layero.find('iframe')[0].contentWindow;
                    let data = obj.data;

                    function extractAddress(address) {
                        // 正则表达式匹配省市区及其前面的内容
                        let regex = "(?<province>[^省]+省|.+自治区|[^澳门]+澳门|北京|[^特别行政区]+特别行政区|重庆|上海|天津|台湾|[^香港]+香港|[^市]+市)?(?<city>[^自治州]+自治州|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县|.+`岛)(?<county>[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+场|.+旗|.+海域|.+岛)";
                        let match = address.match(regex);
                        if (match) {
                            return {
                                province: match[1] || '', // 提取省或自治区或直辖市
                                city: match[2] || '',     // 提取市或自治州
                                county: match[3] || ''    // 提取县、区或旗
                            };
                        } else {
                            return {
                                province: '',
                                city: '',
                                county: ''
                            };
                        }
                    }

                    let address = extractAddress(data.area)
                    body.find("input[name=username]").val(data.username)
                    body.find("input[name=name]").val(data.name)
                    body.find("input[name=phone]").val(data.phone)
                    body.find("input[name=email]").val(data.email)
                    body.find("input[name=age]").val(data.age)
                    body.find("#ID-upload-demo-img").attr('src', baseURL + data.avatar)
                    let province = 'dd[lay-value=' + address.province + ']';
                    let city = 'dd[lay-value=' + address.city + ']';
                    let county = 'dd[lay-value=' + address.county + ']';
                    body.find('#province').siblings("div.layui-form-select").find('dl').find(province).click();
                    body.find('#city').siblings("div.layui-form-select").find('dl').find(city).click();
                    body.find('#county').siblings("div.layui-form-select").find('dl').find(county).click();
                    let male = body.find("input[name=sex][value=1]");
                    let female = body.find("input[name=sex][value=2]");
                    male.prop('checked', data.sex == 1 ? true : false);
                    female.prop('checked', data.sex == 2 ? true : false);
                    form.render(male)
                    form.render(female)
                    iframeWin.layui.form.render();
                }
            })
        }
        window.remove = function (obj) {
            layer.confirm('确定要删除该用户吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'user/getUserById/' + obj.data['userId'],
                    type: 'get',
                    success: function (res) {
                        // 首先检查用户是否已启用
                        if (res.data.status === 0) {
                            layer.msg('该用户已启用，不能删除', {
                                icon: 2,
                                time: 2000
                            });
                            layer.close(loading);
                        } else {
                            // 如果用户未启用，检查是否为登录用户
                            $.ajax({
                                url: baseURL + 'user/getUserByLoginId',
                                type: "get",
                                success: function (res) {
                                    // 如果是登录用户，提示不能删除
                                    if (obj.data.username === res.data.username) {
                                        layer.msg('该用户是登录用户，不能删除', {
                                            icon: 2,
                                            time: 2000
                                        });
                                        layer.close(loading);
                                    } else {
                                        // 如果不是登录用户，执行删除操作
                                        $.ajax({
                                            url: baseURL + 'user/delete/' + obj.data['userId'],
                                            dataType: 'json',
                                            type: 'post',
                                            success: function (result) {
                                                layer.close(loading);
                                                table.reload('user-table', {where: {}, page: {curr: 1}});
                                                if (result.code === 1000) {
                                                    layer.msg(result.msg, {
                                                        icon: 1,
                                                        time: 2000
                                                    }, function () {

                                                    });
                                                } else {
                                                    layer.msg(result.msg, {
                                                        icon: 2,
                                                        time: 2000
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                })
            });
        };
        window.import = function () {

        }
        window.resetPwd = function (obj) {
            layer.confirm('确定要重置密码吗', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'user/resetPwd/' + obj.data['userId'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                layer.close(loading);
                                table.reload('user-table', {where: {}, page: {curr: 1}});
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    }
                })
            });
        }
        window.refresh = function () {
            table.reload('user-table');
        }
        // 动态绑定点击事件（事件委托）
        $(document).on('click', '#uploadExcel', function () {
            // 创建一个隐藏的 file input
            let $input = $('<input type="file" accept=".xls,.xlsx" style="display:none;">');
            $('body').append($input);

            // 选择文件后自动上传
            $input.on('change', function () {
                let file = this.files[0];
                if (!file) return;

                let formData = new FormData();
                formData.append('file', file);

                $.ajax({
                    url: baseURL + 'user/import',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.code === 1000) {
                            layer.msg(res.msg, {icon: 1, time: 2000}, () => table.reload('user-table'));
                        } else {
                            layer.msg(res.msg, {icon: 2, time: 2000});
                        }
                    },
                    error: function () {
                        layer.msg('上传失败', {icon: 2, time: 2000});
                    }
                });

                // 上传完移除 input
                $input.remove();
            });

            // 触发文件选择
            $input.click();
        });
    })
</script>
</body>
</html>
